define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Productdetail, $window, GoPage, $ionicSlideBoxDelegate, $stateParams, GoDialog, Auth, GoShare, $timeout, GoWapAuth, $ionicModal) {
		
		$scope.input = new Object();
		$scope.suit_goods = new Array();
		$scope.input.total = 0;
		var mktprice = '';
		var store = '';
		var bn = '';
		
		$scope.input.count = 0;
		$scope.input.price = 0;
		$scope.input.preferential_price = 0;
		$scope.input.package_price = 0;
		var price = undefined;
		var invalid = false;
		$scope.favorite = false;
		
		$scope.$on('$ionicView.afterEnter', function() {
			$scope.limit = $stateParams.limit;
			$scope.type = $stateParams.type;
			$scope.goods_id = $stateParams.goods_id;
			$scope.init_data(); //必须在定义之后
		}, false)

		//监听数量输入
		$scope.$watch('input.goods_num', function(newValue, oldValue) {
			if(newValue == oldValue) return;
			else if($scope.detail.store != 0) {
				var min_buy = 1;
				if($scope.detail.min_buy != null && $scope.detail.min_buy != 0)
					min_buy = parseInt($scope.detail.min_buy);
				if($scope.detail.max_count != undefined)
					var max_count = $scope.detail.max_count > $scope.detail.store ? $scope.detail.store : $scope.detail.max_count;
				else
					var max_count = $scope.detail.store;
				if(newValue > max_count) {
					$scope.input.goods_num = max_count;
					return;
				}
				if(newValue == undefined) {
					$scope.input.goods_num = min_buy;
					return;
				}
			} else {
				$scope.input.goods_num = 0;
			}
		})
		
		//页面离开，分享关闭
		$scope.$on('$ionicView.afterLeave', function() {
			$scope.closeGuidShare();
		}, false);
		
		//跳转到商品详情页。show_consult/:show_discuss/:show_selllog
		$scope.onshow_productInfo = function() {
			GoPage.go_states("product_info", {
				"id": 0,//哪个tab
				"goods_id": $scope.detail.goods_id,
				"show_consult": $scope.detail.show_consult,
				"show_discuss": $scope.detail.show_discuss,
				"show_selllog": $scope.detail.show_selllog
			});
		}
		
		//上拉跳转到商品详情
		$scope.isLoad = false;
		$scope.doRefreshMore = function(){
			$scope.isLoad = true;
			$scope.$broadcast('scroll.infiniteScrollComplete');
			$timeout(function() {
				$scope.isLoad = false;
			}, 3000);
			$scope.onshow_productInfo();
		}
		
		$scope.onshow_first = function() {
			GoPage.go_states("first", {
				"store_id": $scope.detail.store_id
			});
		}
		
		//商品详情页
		$scope.go_productdetail = function(goods_id) {
			var limit = 0;
			if($scope.detail.isshow == false)
				limit = 1;
			GoPage.go_states("productdetail", {
				"goods_id": goods_id,
				"type": $scope.type,
				"limit": limit
			});
		}
		
		//显示“请选择”型号等字样
		$scope.init_show_name = function(data){
			if(!data.specification) return;
			for(var i=0;i<data.specification.length;i++){
				data.specification[i].show_name = "请选择"+data.specification[i].name;
			}
		}
		
		//选择配置。index为group.goods的下标，目前只有一个配件组
		$scope.chooseSuitGoods = function(index,$event){
			$event.stopPropagation();//阻止事件冒泡
			var curGroup = $scope.detail.group[0];//地址传递
			var curGoods = curGroup.goods[index];//地址传递
			var checked = curGoods.checked;
			var group_price = 0;//优化价
			if(curGoods.group_price != undefined){
				group_price = parseFloat(curGoods.group_price);
			}
			var mktprice =  parseFloat(curGoods.mktprice);//市场价
			if(checked){//减
				curGoods.checked = false;
				$scope.input.count -= 1;
				$scope.input.price -= mktprice;
				$scope.input.package_price -= group_price;
				$scope.input.preferential_price -= mktprice - group_price;
			}else{//添加
				curGoods.checked = true;
				curGoods.count = curGroup.min_count;
				$scope.input.count += 1;
				$scope.input.price += mktprice;
				$scope.input.package_price += group_price;
				$scope.input.preferential_price += mktprice - group_price;
			}
		}
		

		//配件加1
		$scope.productNumber_add = function(id) {
			for(var i = 0; i < $scope.suit_goods.length; i++) {
				if($scope.suit_goods[i].id == id && $scope.suit_goods[i].is_price == true) {
					$scope.suit_goods[i].num += 1;
					$scope.input.total += $scope.suit.goods[i].suit_price;
				}
			}
		}
		
		$scope.goods_add = function() {
			var min_buy = 1;
			if($scope.detail.min_buy != null && $scope.detail.min_buy != 0)
				min_buy = $scope.detail.min_buy;
			$scope.input.goods_num += parseInt(min_buy);
			if($scope.detail.max_count != undefined)
				var max_count = $scope.detail.max_count > $scope.detail.store ? $scope.detail.store : $scope.detail.max_count;
			else
				var max_count = $scope.detail.store;
			if($scope.input.goods_num > max_count)
				$scope.input.goods_num = parseInt(max_count);
		}
		
		$scope.goods_reduce = function() {
			var min_buy = 1;
			if($scope.detail.min_buy != null && $scope.detail.min_buy != 0)
				min_buy = $scope.detail.min_buy;
			if($scope.input.goods_num > 0)
				$scope.input.goods_num -= parseInt(min_buy);
		}
		
		$scope.get_product = function(type) {
			if($scope.detail.store == 0) {
				GoDialog.toast("当前选中的" + $scope.detail.name + "规格没有库存了，请选择其他规格");
				return;
			}
			var product = new Array();
			var adjunct = new Array();
			if(type != 'coupon' && type != 'package') {//检测是否选有所有规格
				if($scope.detail.specification != undefined) {
					for(var i = 0; i < $scope.detail.specification.length; i++) {
						if($scope.detail.specification[i].checked != true) {
							GoDialog.toast("请为商品的" + $scope.detail.specification[i].name + "选值");
							return;
						}
					}
				} else {
					$scope.product_id = $scope.detail.product_id;
				}
				if($scope.detail.group != undefined) {
					for(var i = 0; i < $scope.detail.group.length; i++) {
						for(var n = 0; n < $scope.detail.group[i].goods.length; n++) {
							if($scope.detail.group[i].goods[n].checked == true) {
								var o = adjunct.length;
								adjunct[o] = {
									"group_id": $scope.detail.group[i].id,
									"product_id": $scope.detail.group[i].goods[n].product_id,
									"num": $scope.detail.group[i].goods[n].count
								}
							}
						}
					}
				}
				var i = product.length;
				product[i] = {
					"product_id": $scope.product_id,
					"adjunct": adjunct
				}
			}
			if(!$scope.input.goods_num) {
				GoDialog.toast("请填写购买数量");
				return;
			}
			Productdetail.set_cart($scope.detail.goods_id, $scope.type, $scope.product_id, adjunct, $scope.input.goods_num, $scope.status, function(data) {
				if(data.success == true) {
					if($scope.status == 'fastbuy') {
						GoPage.go_states("afsrue", {
							"type": $scope.type,
							"status": $scope.status
						});
					}else{
						GoPage.go_states("tab_cart");
					}
				} else {
					GoDialog.alert("提示",data.msg);
				}
			})
		}
		
		//加入购物车
		$scope.set_cart = function() {
			if($scope.type == 'goods' || $scope.type == 'coupon' || $scope.type == 'package')
				$scope.status = '';
			else if($scope.type != '' && $scope.type != undefined)
				$scope.status = 'fastbuy';
			$scope.get_product($scope.type);
		}
		
		//立即购买
		$scope.fast_buy = function() {
			$scope.status = 'fastbuy';
			$scope.get_product($scope.type);
		}
		
		//显示单个价格
		$scope.init_is_price = function() {
			var is_single = false;
			if($scope.detail.specification) {
				if($scope.detail.specification.length <= 1)
					is_single = true;
			} else {
				is_single = true;
			}
			if($scope.detail.goods_specification) {
				if(($scope.detail.goods_specification.length == 1) && is_single)
					$scope.is_price = true;
			} else{
				$scope.is_price = false;
			}
		}
		
		//购买数量
		$scope.init_buy_num = function() {
			if($scope.detail.min_buy != null && $scope.detail.min_buy != 0){
				$scope.minBuyNum = parseInt($scope.detail.min_buy);//购买基数
				$scope.input.goods_num = parseInt($scope.detail.min_buy);
			}
			else
				$scope.input.goods_num = 1;
		}
		
		$scope.init_num = function() {
			if($scope.detail.mktprice != undefined)
				mktprice = $scope.detail.mktprice;
			if($scope.detail.store != undefined)
				store = $scope.detail.store;
			if($scope.detail.price != undefined)
				price = $scope.detail.price;
			if($scope.detail.bn)
				bn = $scope.detail.bn;
		}
		
		//初始化
		$scope.init_data = function() {
			$scope.user_id = Auth.get_user_id();
			$scope.fast_buy_name = '立即购买';
			$scope.buy_name = '加入购物车';
			if($scope.user_id != 5) {
				$scope.fast_buy_name = '立即采购';
				$scope.buy_name = '加入采购车';
			}
			Productdetail.product_detail($scope.goods_id, $scope.limit, function(data) {
				console.log(data)
				if(data != null) {
					invalid = data.invalid;
					$scope.detail = data;
					if(data.favorite == '1') {
						$scope.favorite = true;
					}
					if(data.mktprice)
						$scope.detail.mktprice = data.mktprice;
					$scope.init_is_price();
					$scope.init_buy_num();
					$scope.init_num();
					$scope.init_show_name(data);
					$scope.price = $scope.detail.price;
					$scope.go_share_wx();
					$ionicSlideBoxDelegate.$getByHandle('advs-handle').update(); //解决无法加载
					$ionicSlideBoxDelegate.$getByHandle('advs-handle').loop(true); //循环
				} else {
					GoDialog.alert("提示","暂无商品信息，您可以联系平台....",function(){
						GoPage.go_back();
					});
					$scope.detail = new Object();
				}
			});
		}
		
		//选择某个规格
		$scope.selectSpec = function(index){
			var curSpec = $scope.detail.specification[$scope.selectedSpecIndex];
			var curDetail = curSpec.detail[index];//$scope.specList.detail[index]也是一样的
			var isChecked = curDetail.checked;
			var specification_id = curDetail.specification_id;
			for (var i=0;i<curSpec.detail.length;i++) {
				if(i!=index){
					curSpec.detail[i].checked = false;
					curSpec.checked = false;
				}
			}
			if(isChecked){//只控制效果显示
				curDetail.checked = false;
				curSpec.checked = false;
				curSpec.show_name = "请选择"+curSpec.name;
				$scope.selectedSpecDetailIndex = -1;//如果没有选择任何规则，则赋值为-1
			}else{//选中
				curDetail.checked = true;
				curSpec.checked = true;
				curSpec.show_name = curDetail.name;
				curSpec.chekced_name = specification_id;//获取库存时要用
				$scope.selectedSpecDetailIndex = index;
			}
		}
		
		//确定选中的规格
		$scope.confirmSpec = function() {
			$scope.closeModal_spec();//关闭弹窗
			if($scope.selectedSpecDetailIndex==undefined||$scope.selectedSpecDetailIndex==-1) return;//如果没有选择规格
			var is_product = false;
			var count = 0;
			var index1 = '';
			var comp = new Array();
			var l = $scope.detail.specification.length;
			var j = $scope.detail.goods_specification.length;
//			var curSpec = $scope.detail.specification[$scope.selectedSpecIndex];
//			var curDetail = curSpec.detail[$scope.selectedSpecDetailIndex];
//			var specification_id = curDetail.specification_id;
			
			//如果商品不止一种货品
//			if(j != 1) {
				for(var i = 0; i < l; i++) {
					if($scope.detail.specification[i].checked == true)
						count++;
				}
				if(count == l) {
					for(var i = 0; i < $scope.detail.specification.length; i++) {
						var o = comp.length;
						comp[o] = $scope.detail.specification[i].chekced_name;
					}
					for(var i = 0; i < $scope.detail.goods_specification.length; i++) {
						if(comp.toString() == $scope.detail.goods_specification[i].specification_id.toString()) {
							is_product = true;
							if(invalid != true)
								$scope.detail.invalid = $scope.detail.goods_specification[i].invalid;
							var index1 = i;
							break;
						} else {
							if(invalid != true)
								$scope.detail.invalid = false;
							is_product = false;
						}
					}
					if(is_product == true) {
						$scope.detail.bn = $scope.detail.goods_specification[index1].bn;
						$scope.product_id = $scope.detail.goods_specification[index1].product_id;
						if($scope.detail.goods_specification[index1].price != undefined) {
							if($scope.detail.price|| $scope.detail.price==0){
								$scope.input.price -= parseFloat($scope.detail.price);
							$scope.input.package_price -= parseFloat($scope.detail.price) ;
							}
							$scope.detail.mktprice = $scope.detail.goods_specification[index1].market_price;
							$scope.detail.price = $scope.detail.goods_specification[index1].price;
							$scope.input.price += parseFloat($scope.detail.price);
							$scope.input.package_price += parseFloat($scope.detail.price);
						} else {
							if($scope.detail.mktprice){
								$scope.input.price -= parseFloat($scope.detail.mktprice);
								$scope.input.package_price -= parseFloat($scope.detail.mktprice);
							}
							$scope.detail.price = $scope.detail.goods_specification[index1].market_price;
							$scope.detail.mktprice = '';
							$scope.input.price += parseFloat($scope.detail.price);
							$scope.input.package_price += parseFloat($scope.detail.price);
						}

						$scope.detail.store = $scope.detail.goods_specification[index1].store;
						if($scope.detail.max_count != undefined)
							var max_count = $scope.detail.max_count > $scope.detail.store ? $scope.detail.store : $scope.detail.max_count;
						else
							var max_count = $scope.detail.store;
						if($scope.input.goods_num > max_count)
							$scope.input.goods_num = parseInt(max_count);
						$scope.is_price = true;
					} else {
						if(invalid != true)
							$scope.detail.invalid = false;
						$scope.is_price = false;
						$scope.detail.mktprice = mktprice;
						$scope.input.goods_num = 0;
						GoDialog.toast('所选规格没有库存');
					}
				} else {
					$scope.is_price = false;
					$scope.detail.price = price;
					$scope.detail.mktprice = mktprice;
					$scope.detail.store = store;
					$scope.detail.bn = bn;
				}
//			}
		}
		/**********选择某个规格*************/
		
		
		//收藏商品
		$scope.add_favorite = function() {
			if(!$scope.user_id) {
				GoDialog.alert("提示","请登录后再收藏！",function(){
					GoPage.go_states("t-login");
				});
				return;
			}
			if(!$scope.favorite) {
				Productdetail.add_favorite($scope.goods_id, function(data) {
					if(data.success == true) {
						$scope.favorite = true;
						GoDialog.toast("商品收藏成功！");
					} else
						GoDialog.toast(data.msg);
				})
			} else {
				Productdetail.del_favorite($scope.goods_id, function(data) {
					if(data.success == true) {
						$scope.favorite = false;
						GoDialog.toast("商品取消收藏成功！");
					} else
						GoDialog.toast(data.msg);
				})
			}
		}
		
		//分享（自定义每个页面的参数）
		$scope.go_share = function(index) {
			$scope.closeModal_share();//关闭弹窗
			var param = new Object();
			if($scope.detail) {
				param.title = $scope.detail.name ? $scope.detail.name : undefined;
				param.desc = $scope.detail.brief ? $scope.detail.brief : undefined;
				param.thumb = $scope.detail.title_images ? $scope.detail.title_images[0].image.s_url : undefined;
				param.link = 'productdetail/' + $scope.goods_id + '/' + $scope.type + '/' + $scope.limit;
			}
			GoShare.do_share(param, index);
		}

		//分享（自定义每个页面的参数）
		$scope.go_share_wx = function() {
			//分享打开
			GoWapAuth.execisoff(false);
			//设置分享
			var param = new Object();
			if($scope.detail) {
				param.title = $scope.detail.name ? $scope.detail.name : undefined;
				param.desc = $scope.detail.brief ? $scope.detail.brief : undefined;
				param.thumb = $scope.detail.title_images ? $scope.detail.title_images[0].image.l_url : undefined;
				param.link = 'productdetail/' + $scope.goods_id + '/' + $scope.type + '/' + $scope.limit;
			}
//			console.log(param)
			GoWapAuth.execshare(param);
		}
		
		/***************选择规格**************/
		$ionicModal.fromTemplateUrl("templates/modal/specList.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_spec = modal;
		});
		//打开
		$scope.openModal_spec = function(index) {
			$scope.specList = $scope.detail.specification[index];
			$scope.selectedSpecIndex = index;//规格组的下标，$scope.detail.specification[$scope.selectedSpecIndex];
//			console.log($scope.specList)
			$scope.modal_spec.show();
		}
		//隐藏
		$scope.closeModal_spec = function() {
			$scope.modal_spec.hide();
		}
		
		/***************领取优惠券**************/
		$ionicModal.fromTemplateUrl("templates/modal/couponListModal.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_coupon = modal;
		});
		//打开
		$scope.openModal_coupon = function() {
			$scope.modal_coupon.show();
		}
		//隐藏
		$scope.closeModal_coupon = function() {
			$scope.modal_coupon.hide();
		}
		
		//领取优惠券
		$scope.get_coupon = function(cpns_id){
			Productdetail.get_coupon(cpns_id, function(data) {
				GoDialog.toast(data.msg);
			})
		}
		/***************领取优惠券**************/
		
		/***************分享**************/
		$ionicModal.fromTemplateUrl("templates/modal/keyshare_modal.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_share = modal;
		});
		//打开
		$scope.openModal_share = function() {
			if($scope.openGuidShare()) {
				$scope.modal_share.show();
			}
		}
		//隐藏
		$scope.closeModal_share = function() {
			$scope.modal_share.hide();
		}
		/***************分享**************/
		
		/***********显示《客服》**********/
		$ionicModal.fromTemplateUrl("templates/modal/customer_service.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_customer = modal;
		});
		//打开
		$scope.openModal_customer = function() {
			//客服
			Productdetail.contact_show($scope.detail.store_id, function(data) {
				if(!data||data.cusphone.length<1){
					GoDialog.alert("提示","店家暂时还没有设置客服哦");
					return;
				}
				$scope.customerList = data;
				$scope.modal_customer.show();
			})
		}
		//隐藏
		$scope.closeModal_customer = function() {
			$scope.modal_customer.hide();
		}
		//选择客服
		$scope.selectCustomer = function(index){
			$scope.customerList_index = index;
		}
		//联系客服
		$scope.do_tel = function() {
			$scope.closeModal_customer();
			var param = $scope.customerList.cusphone[$scope.customerList_index];
			if(param.type == 2) {
				$window.location.href = "tel:" + param.value;
			} else if(param.type == 1) {
				if(param.isonline == '0') {
					GoPage.go_txcall3(param.id, param.code, param.vvckey);
				} else {
					GoPage.go_txcall2($scope.detail.store_id, $scope.detail.store_id, param.id, param.code, param.vvckey);
				}
			}
		}
		/***********显示《客服》**********/
		
		
		//优惠信息,超过3个。type：1订单促销 ；2商品促销
		$scope.showMoreProInfo = function(type){
			if(type==1){
				$scope.isMoreProInfo_order = !$scope.isMoreProInfo_order;
			}else{
				$scope.isMoreProInfo_goods = !$scope.isMoreProInfo_goods;
			}
		}
		
		
	}

	controller.$inject = ['$scope', 'Productdetail', '$window', 'GoPage', '$ionicSlideBoxDelegate', '$stateParams', 'GoDialog', 'Auth', 'GoShare', '$timeout','GoWapAuth', '$ionicModal'];

	return app.registerController("productdetailctrl", controller);
});